package com.lzb.browser.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.browser.BaseNoModelFragment;
import com.lzb.browser.Content;
import com.lzb.browser.R;
import com.lzb.browser.adapter.RecordAdapter;
import com.lzb.browser.bean.CollectBean;
import com.lzb.browser.bean.RecordBean;
import com.lzb.browser.databinding.FragmentRecordBinding;
import com.lzb.browser.utils.AppSpUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RecordFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RecordFragment extends BaseNoModelFragment<FragmentRecordBinding> implements View.OnClickListener, OnItemClickListener {

    private RecordAdapter recordAdapter;
    private List<RecordBean> listShow = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.fragment_record;
    }

    @Override
    protected void initView() {
        mDataBinding.tvDelete.setOnClickListener(this);

        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext));
        recordAdapter = new RecordAdapter();
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.tvDelete) {//全部删除
            if (listShow.size() == 0) return;
            AppSpUtils.saveRecordList(new ArrayList<>());
            ToastUtils.showShort(getString(R.string.delete_suc));
            getData();
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        Intent intent = new Intent();
        intent.putExtra(Content.url, listShow.get(position).getUrl());
        getActivity().setResult(Content.SEARCH_URL_RESULT, intent);
        getActivity().finish();
    }

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        listShow.clear();
        List<RecordBean> listSp = AppSpUtils.getRecordList();
        if (listSp != null && !listSp.isEmpty()) {
            listShow.addAll(listSp);
            recordAdapter.setList(listShow);
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
            mDataBinding.tvRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
            mDataBinding.tvRecordNoData.setVisibility(View.VISIBLE);
        }
    }

}